package com.example.demo.aop;

import com.example.demo.base.AopException;
import com.example.demo.vo.DemoVO;
import com.example.demo.base.ReqParam;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Component
public class DemoAspect {

    private Logger logger = LogManager.getLogger(getClass());

    @Pointcut("execution(public * com.example.demo.service.DemoService.update*(..)) || execution(public * com.example.demo.service.DemoService.saveTest3(..))")
    public void checkCompanyId() {
    }

    @Before("checkCompanyId()")
    public void checkCompanyId(JoinPoint joinPoint) throws Throwable {

        Object[] args = joinPoint.getArgs();
        String companyId = "";
        try {
            //从参数中获取companyId，args[0]代表第一个参数
            if(args != null && args.length != 0){
                if(args[0] instanceof String){     //假如是String类型
                    companyId = (String)args[0];
                }else if(args[0] instanceof Map){  //假如是Map类型
                    Map map = (Map)args[0];
                    companyId = map.get("companyId") != null ? map.get("companyId").toString() : "";
                }else if(args[0] instanceof DemoVO){  //假如是自定义DemoVO类
                    DemoVO demoVO = (DemoVO)args[0];
                    companyId = demoVO.getCompanyId();
                }else if(args[0] instanceof ReqParam){  //假如是自定义ReqParamVO类
                    ReqParam reqParamVO = (ReqParam)args[0];
                    DemoVO demoVO = (DemoVO)reqParamVO.getData();
                    companyId = demoVO.getCompanyId();
                }
            }
        } catch (Exception e) {
            logger.log(Level.ERROR, "获取companyId出现异常，异常信息：{}", e);
            throw new AopException("获取companyId出现异常");
        }

        if(StringUtils.isEmpty(companyId)){
            logger.log(Level.ERROR, "companyId校验不通过，companyId为空");
            throw new AopException("companyId校验不通过，companyId为空");
        }

        if (!verifyCompanyId(companyId)) {
            logger.log(Level.INFO, "companyId({})校验不通过，简单说明校验不通过的原因，方便排查问题", companyId);
            throw new AopException("companyId("+companyId+")校验不通过，简单说明校验不通过的原因，方便排查问题");
        }

    }

    private boolean verifyCompanyId(String companyId){
        //根据业务要求校验companyId，校验通过返回true，否则返回false
        return true;
    }

}
